package com.vf.s.mvc.biz.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.vf.core.controller.BaseController;
import com.vf.core.model.ZtreeNode;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.biz.BizFlight;
import com.vf.s.common.render.FlightRender;
import com.vf.s.mvc.biz.service.PointService;

public class BizFlightController extends BaseController {
	
	
	@Inject
	private PointService srv;
	
	public void index() {
		this.set("sceneId", this.get("sceneId"));
		render("index.html");
	}

	public void common() {
		this.set("sceneId", this.get("sceneId"));
		render("common.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String name = getPara("name");
		String sceneId = getPara("sceneId");
		String menuId = getPara("menuId");
		
		String sqlExceptSelect = " from " + BizFlight.TABLE_NAME + " o where 1=1 ";
		
		if (!StrKit.isBlank(name)) {
			sqlExceptSelect += " and o.name like '%" + name + "%'  ";
		}
		if (!StrKit.isBlank(sceneId)) {
			sqlExceptSelect += " and o.sceneId='"+sceneId+"' ";
		}
		sqlExceptSelect += "  order by   o.sort desc ";
		Page<BizFlight> page = BizFlight.dao.paginate(pageNumber, pageSize, "select o.*,(CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM BIZ_SCENE_MENU_ITEM WHERE type='flight' and menuId='"+menuId+"' and objId=o.id)>0 THEN TRUE ELSE  FALSE END ) AS checked  ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());	
	}
	
	public void getAllList() {
		String sceneId=this.get("sceneId");
		List<BizFlight> bizFlights = BizFlight.dao.find("select * from "+BizFlight.TABLE_NAME+" where sceneId=? and parentId='root' ",sceneId);
		if(bizFlights!=null && bizFlights.size()>0) {
			renderSuccess("查询成功！", bizFlights);
		}else {
			renderError("数据不存在！");
		}
	}
	
	public void getTree() {
		boolean open = true;// 是否展开所有
		boolean ifOnlyLeaf = false;// 是否只选叶子
		if (StrKit.notBlank(getPara("ifOnlyLeaf"))) {// 是否查询所有孩子
			if ("1".equals(getPara("ifOnlyLeaf"))) {
				ifOnlyLeaf = true;
			}
		}
		String type=getPara("type");
		List<BizFlight> modelList = BizFlight.dao.getChildrenAllTree("root", type);
		List<ZtreeNode> nodelist = BizFlight.dao.toZTreeNode(modelList, open, ifOnlyLeaf);// 数据库中的菜单
		renderJson(nodelist);
	}
	
	public void getAsyncTreeData() {
		String id=this.get("id", "root");
		String sceneId=this.get("sceneId");
		String sql = "SELECT a.*,(CASE WHEN (select count(id) from biz_flight where a.id=parentId ) >0 THEN true ELSE false END) AS isParent FROM biz_flight a where a.parentId=? and sceneId=? order by a.sort asc ";
		List<BizFlight> olist = BizFlight.dao.find(sql,id,sceneId);
		List<ZtreeNode> nodelist = new ArrayList<ZtreeNode>();
		for (BizFlight o : olist) {
			ZtreeNode node = BizFlight.dao.toZTreeNode(o);
			node.setIsParent(StrKit.equals("1",o.get("isParent")+"")?true:false);
			node.setType(o.getType());
			nodelist.add(node);
		}
		renderJson(nodelist);
	}
	
	
	public void save() {
		BizFlight model = getModel(BizFlight.class);
		BizFlight dbBizFlight=BizFlight.dao.findById(model.getId());
		if(dbBizFlight!=null) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		}else {
			if(StrKit.isBlank(model.getId()))
				model.setId(UuidUtil.getUUID());
			if(StrKit.isBlank(model.getParentId()))
				model.setParentId("root");
			if (model.save()) {
				renderSuccess("保存成功！",model);
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	public void delete() throws Exception {
		String id = getPara("id");
		Page<BizFlight> page=BizFlight.dao.paginate(1, 1, "SELECT * "," FROM "+BizFlight.TABLE_NAME+" WHERE PARENTID=? ",id);
		if (page.getTotalRow()==0) {
			BizFlight bizFlight=BizFlight.dao.findById(id);
			if(bizFlight!=null) {
				if (bizFlight.delete()) {
					renderSuccess("删除成功！");
				} else {
					renderError("删除失败！");
				}
			}
			else {
				renderError("无效操作，数据不存在!");
			}

		} else {
			renderError("当前节点有子节点,不允许删除!");
			return;
		}
	}

	
	public void getLayerById() throws Exception {
		String id = getPara("id");
		BizFlight bizFlight=BizFlight.dao.findById(id);
		if (bizFlight!=null) {
			renderSuccess("成功！",bizFlight);
		} else {
			renderError("数据已经不存在！");
		}
	}
	
	@Before(Tx.class)
	public void savePoints(){
		String points = getPara("points");
		try {
			if(!StrKit.isBlank(points)) {
				JSONArray arr=JSONArray.parseArray(points);
				int i=1;
				for(Object point:arr) {
			        JSONObject obj= (JSONObject) point;
			        String id =  obj.getString("id");
			        String parentId =  obj.getString("parentId");
			        int sort=obj.getInteger("sort");
			        BizFlight bizFlight=new BizFlight();
			        bizFlight.setId(id);
			        bizFlight.setParentId(parentId);
			        bizFlight.setName("飞行点【"+i+"】");
			        bizFlight.setSort(sort);
			        bizFlight.save();
			        i++;
				}
			}
			renderSuccess("保存成功！");
		}catch (Exception e) {
			renderError("保存失败！");
		}
	}
	
//	public void getFlightForMenu() {
//		String menuId=this.getPara("menuId");
//		String sceneId=this.getPara("sceneId");
//		List<BizFlight> bizFlights =BizFlight.dao.find(
//				"select * from "+BizFlight.TABLE_NAME+" where sceneId=? and id in (select objId from "+BizSceneMenuItem.TABLE_NAME+" where type='flight' and menuId=?) ",sceneId,menuId);
//		if(bizFlights!=null && bizFlights.size()>0) {
//			renderSuccess("查询成功！", bizFlights);
//		}else {
//			renderError("菜单未配置漫游路线！");
//		}
//	}
	
	public void getFlightRender() {
		String flightId=this.getPara("flightId");
		
		BizFlight bizFlight=BizFlight.dao.findById(flightId);
		if(bizFlight!=null) {
			List<BizFlight> list=BizFlight.dao.find("SELECT * FROM "+BizFlight.TABLE_NAME+" WHERE parentId=? ORDER BY SORT ASC ",bizFlight.getId());
			if(list!=null && list.size()>0) {
				Map<String,Object> map=new HashMap<String,Object>();
				List<FlightRender> flightRenders=new LinkedList<FlightRender>();
				for(BizFlight flight:list) {
					FlightRender flightRender=new FlightRender();
					flightRender.setFlight(flight);
				//	flightRender.setPoint(srv.getPointRender(flight.getId()));
					flightRenders.add(flightRender);
				}
				map.put("flight", bizFlight);
				map.put("points", flightRenders);
				renderSuccess("查询成功！",map);
			}else {
				renderError("请定义飞行点！");
			}
		}else {
			renderError("数据不存在！");
		}
	}
	
}
